var model = require('../model/userSchema');
module.exports = function(app) {

	var isUser;

	//检测用户名是否注册
	app.get('/reg/isUserName', function(req, res) {
		var email = req.query.email;
		if (!email) {
			res.json({code: '902', msg: '请输入邮箱'});
			return;
		}
		model.findOne({email: email}, function(err, docs) {
			if (err) {
				console.log(err)
			}else {
				if (docs) {
					res.json({code: '901', msg: '用户名已存在'})
				}else {
					isUser = true;
					res.json({code: '0'})
				}
			}
		})

	})

	// 注册用户
	app.get('/reg', function(req, res) {
		if (isUser) {
			var email = req.query.email,
				password = req.query.password,
				userName = req.query.userName;
			if (!email) {
				res.json({code: '902', msg: '邮箱号码不能为空'});
				return;
			}
			if (!password) {
				res.json({code: '902', msg: '密码不能为空'});
				return;
			}
			if (!userName) {
				res.json({code: '902', msg: '用户昵称不能为空'});
				return;
			}
			var data = {
				email: email,
				password: password,
				userName: userName
			}
			model.create(data, function(err, docs) {
				if (err) {
					res.send(err);
				} else {
					res.json({code: '0', msg: '注册成功'})
			 		isUser = false;
				}
			})
		}else{
			res.json({code: '902', msg: '用户名未验证成功'})
		}
	});

	// 登录
	app.get('/get/login', function(req, res){
		var email = req.query.email,
			password = req.query.password;
		if(!email && !password) {
			res.json({code: '902', msg: '请填写用户名和密码'});
			return;
		}
		model.findOne({email: email, password: password}, function(err, docs) {
			if (docs) {
				req.session.user_id = docs._id;
				req.session.user_name = docs.userName;
				console.log(req.session);
				res.json({code: '0', msg: '登录成功'})
			}else {
				res.json({code: '902', msg: '用户名或密码错误'})
			}
		})
	})

	app.get('/login', function(req, res) {
		res.render('reg');
	})
}